package com.gaga.common.utils;


import cn.hutool.core.codec.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {
    // 密匙
//    private static final String KEY = "3de17802-d14e-4bde-80ee-54f02d4b5109";
    private static final String KEY = "Yv+A7casjhgCl9wzpb9AHzH/N1s7faCb";
    // 偏移量
    private static final String OFFSET = "5e8y6w45ju8w9jq8";
    // 编码
    private static final String ENCODING = "UTF-8";
    //算法
    private static final String ALGORITHM = "AES";
    // 默认的加密算法
    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";


    /**
     * 加密
     *
     * @param data
     * @return
     * @return String
     * @throws Exception
     */
    public static String encrypt(String data) {
        byte[] encrypted = new byte[0];
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("ASCII"), ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            encrypted = cipher.doFinal(data.getBytes(ENCODING));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Base64.encode(encrypted);
    }

    /**
     * 解密
     *
     * @param data
     * @return
     * @return String
     * @throws Exception
     */
    public static String decrypt(String data) throws Exception {
        byte[] encrypted;
        String decryptResult = null;
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("ASCII"), ALGORITHM);
        //使用CBC模式，需要一个向量iv，可增加加密算法的强度
        IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        byte[] buffer = Base64.decode(data);
        encrypted = cipher.doFinal(buffer);
        //此处使用BASE64做转码。
        decryptResult = new String(encrypted, ENCODING);
        return decryptResult;
    }


    public static void main(String[] args) throws Exception {


        System.out.println(AESUtils.encrypt("c406a055"));//CwOx6tV9THfU18mTX8kpuw==
        System.out.println(AESUtils.decrypt("hsGTePEjmyuVNWlyzFs87Q=="));
        long length = Cipher.getMaxAllowedKeyLength("AES/CBC/PKCS5Padding");
        System.out.println(length);

        String key = "3de17802-d14e-4bde-80ee-54f02d4b5109";
        String plainText = "a36f69ab-6829-468a-8d93-90fda2f1149d";

        System.out.println(encrypt(plainText));
    }
}
